//
//  PictureView.m
//  homework
//
//  Created by dllo on 16/6/13.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "PictureView.h"
#import "MyScrollView.h"

@interface PictureView()<UIScrollViewDelegate>

@property (nonatomic, retain) MyScrollView *scrollView;

@property (nonatomic, retain) UIPageControl *pageControl;

@end

@implementation PictureView

-(void)dealloc
{
    [_imageArray release];
    [_scrollView release];
    [_pageControl release];
    [super dealloc];
}


-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        /**在初始化的时候对所有的属性进行初始化*/
        self.imageArray = [NSArray array];
        [self createScrollView];
        [self createPageControl];
        
        
    }
    return self;
}

-(void)createScrollView
{
    self.scrollView = [[MyScrollView alloc]initWithFrame:self.bounds];
    
    self.scrollView.backgroundColor = [UIColor lightGrayColor];
    
    [self addSubview:self.scrollView];
    
    self.scrollView.contentOffset = CGPointMake(CGRectGetWidth(self.bounds), 0);
    
    self.scrollView.delegate = self;
}

-(void)createPageControl
{
    /**创建pageControl,并添加到父视图*/
    self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.bounds) / 5 * 3, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) / 5 * 2)];
    
    [self addSubview:self.pageControl];
    
    self.pageControl.numberOfPages = self.imageArray.count;
    
    [self.pageControl release];
    
    [self.pageControl addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
}

/**UIScrollView的代理方法*/
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.pageControl.currentPage = scrollView.contentOffset.x / CGRectGetWidth(self.bounds);
    
    if (scrollView.contentOffset.x > CGRectGetWidth(self.bounds) * 2) {
        
        _scrollView.contentOffset = CGPointMake(0, 0);
        
    }else if(scrollView.contentOffset.x < CGRectGetWidth(self.bounds)){
        
        _scrollView.contentOffset = CGPointMake(CGRectGetWidth(self.bounds) * 2, 0);
    }
    
    
    
    
}

/**pageControl的点击方法*/
-(void)pageAction:(UIPageControl *)pageControl
{
    self.scrollView.contentOffset = CGPointMake(pageControl.currentPage * CGRectGetWidth(self.bounds), 0);
}

/**重写属性的setter方法*/
-(void)setImageArray:(NSArray<UIImage *> *)imageArray
{
    if (_imageArray != imageArray) {
        [_imageArray release];
        _imageArray = [imageArray retain];
    }
    /**添加图片*/
    [self.scrollView addPicture:_imageArray];
    
    //
    self.pageControl.numberOfPages = _imageArray.count - 2;
}


@end
